package Java攻略._2_java_util_function包._2_Supplier接口;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class _5_在集合中查找名称 {

    public static void main(String[] args) {

        List<String> names = Arrays.asList("Mal", "Wash", "Kaylee", "Inara",
                "Zoë", "Jayne", "Simon", "River", "Shepherd Book");

        Optional<String> first = names.stream()
                .filter(name -> name.startsWith("C"))
                .findFirst();

        // 打印Optional.empty
        System.out.println(first);

        // 打印字符串"None"
        System.out.println(first.orElse("None"));

        // 即便找到指定的名称，仍然使用逗号分隔集合
        String s = first.orElse(String.format("No result found in %s",
                names.stream().collect(Collectors.joining(","))));
        System.out.println(s);

        // 仅当Optional为空时，才使用逗号分隔集合
        String s1 = first.orElseGet(() -> String.format("No result found in %s",
                names.stream().collect(Collectors.joining(","))
        ));
        System.out.println(s1);

    }
}
